// pages/address/list/index.js
import { reqAddressList, reqDeleteAddress } from '../../../api/address'
import { swiperCellBehaviors } from '@/behaviors/swiperCell'

const app = getApp()

Page({

    behaviors: [swiperCellBehaviors],

  // 页面的初始数据
  data: {
    addressList: [],
  },

  // 去编辑页面
  toEdit(event) {
    //获取需要更新的地址的id
    const { id } = event.currentTarget.dataset

    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },

  async getAddressList() {
      const { data: addressList } = await reqAddressList()
      this.setData({ addressList })
  },

  // 删除收货地址
  async delAddressList(event) {
    const { id } = event.currentTarget.dataset
    const modalRes = await wx.modal({
        content: '您确定删除该收货地址吗'
    })

    if(modalRes) {
        await reqDeleteAddress(id)
        wx.toast({ title: '收货地址删除成功' })
        
        // 重新获取收获地址列表
        this.getAddressList()
    }
  },

  onShow() {
      this.getAddressList()
  },

  changeAddress(event) {
      // 判断是否是从订单页面跳转过来的，如果不是不进行操作
      if(this.flag !== '1') 
        return
    
    // 获取点击的地址id
    const addressId = event.currentTarget.dataset.id
    // 在地址表中查找对应id的地址
    const selectAddress = this.data.addressList.find((item) => item.id === addressId)
    // 如果获取成功后将查找到的地址赋值给全局共享地址
    if(selectAddress) {
        app.globalData.address = selectAddress

        wx.navigateBack()
    }

  },

  onLoad(options) {
      this.flag = options.flag 
  }
})
